package cn.itcast.bos.service.impl.take_delivery;

import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.take_delivery.WayBillRepository;
import cn.itcast.bos.domain.take_delivery.WayBill;
import cn.itcast.bos.indexdao.take_delivery.WayBillEsRepository;
import cn.itcast.bos.service.take_delivery.WayBillService;

@Service("wayBillService")
@Transactional
public class WayBillServiceImpl implements WayBillService {
	// 注入dao
	@Autowired
	private WayBillRepository wayBillRepository;
	@Autowired
	private WayBillEsRepository wayBillEsRepository;

	@Override
	// 保存数据
	public void saveWayBill(WayBill wayBill) {
		// TODO Auto-generated method stub
		wayBillRepository.save(wayBill);
		// 向索引库中保存索引数据
		wayBillEsRepository.save(wayBill);
	}

	@Override
	public Page<WayBill> findWayBillPageList(Pageable pageable) {
		// TODO Auto-generated method stub
		return wayBillRepository.findAll(pageable);
	}

	public Page<WayBill> findWayBillPageList(Pageable pageable, String fieldName, String fieldValue) {

		// 检索规则对象(你要做到)
		// QueryBuilder query=null;

		// 规则1：关键字精确匹配term词条
		// 参数：词条所在的映射的位置
		TermQueryBuilder termQuery = QueryBuilders.termQuery(fieldName, fieldValue);

		// 规则2：关键字模糊匹配词条,值支持*和?
		WildcardQueryBuilder wildcardQuery = QueryBuilders.wildcardQuery(fieldName, "*" + fieldValue + "*");

		// 规则3：全字段自动匹配、自动分词、自动检索
		QueryStringQueryBuilder queryStringQuery = QueryBuilders.queryStringQuery(fieldValue)
				// 指定中文ik分词器，先分词再查询
				.analyzer("ik");

		// Query查询规则组合
		// 布尔query：用来组合规则
		BoolQueryBuilder query = QueryBuilders.boolQuery();
		// 检索的时候，该规则必须满足 and
		// query.must(queryBuilder);
		// 该规则必须不满足，排除效果
		// query.mustNot(queryBuilder);
		// 该规则可以满足 or
		// query.should(queryBuilder);

		// should结果更多
		query.should(termQuery);
		query.should(wildcardQuery);
		// query.should(queryStringQuery);

		// 检索查询方法
		// 参数：检索规则的对象
		// wayBillEsRepository.search(QueryBuilder);//不分页，默认es分页
		// 分页检索查询
		return wayBillEsRepository.search(query, pageable);

	}

}
